package com.ktjy.utils;

import com.ktjy.dto.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class JWTUtil {
    @Value("${token.secret}")
    private String secret;
    @Value("${token.expireTime}")
    private int expireTime;
    @Autowired
    RedisTemplate redisTemplate;

    public String generateToken(LoginUser loginUser){
        //登录用户信息
        Map<String,Object> map=new HashMap<>();
        map.put("username",loginUser.getUsername());

        //生成token(jwt令牌)
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256,secret) //指定加密算法和私钥
                .setClaims(map) //设置载荷
                .setIssuedAt(new Date())
                .compact();

        //用户信息保存到redis
        redisTemplate.opsForValue()
                .set(Constants.LOGIN_USER+ loginUser.getUsername(),loginUser,expireTime, TimeUnit.MINUTES);

        return token;
    }

    public Claims parseToken(String token){
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .build()
                .parseClaimsJws(token)
                .getBody();

        return claims;
    }
    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        redisTemplate.opsForValue()
                .set(Constants.LOGIN_USER+ loginUser.getUsername(),loginUser,expireTime, TimeUnit.MINUTES);
        ;
    }


//    public void verifyToken(SysUser sysUser)
//    {
//        long expireTime = sysUser.getExpireTime();
//        long currentTime = System.currentTimeMillis();
//        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
//        {
//            refreshToken(loginUser);
//        }
//    }
}
